#!/usr/bin/perl
use strict;
use warnings;

my $argstr = $0;
foreach (@ARGV) {
    $argstr .= " \"$_\"";
}

my $pp = shift @ARGV;
my $depfile = shift @ARGV;
my @c_files = @ARGV;
my %obj;

open my $outFH, ">$depfile";


foreach my $file (@c_files) {
    my $objfile = $file;
    $objfile =~ s/.*\///;
    $objfile =~ s/\.c$/\.obj/;
    $objfile = "\${OBJ}/$objfile";
    $obj{$objfile} = $file;
}

print $outFH "#Generated using:\n# $argstr\n\n";

print $outFH "OBJ_FILES = " . join(" ", keys(%obj)) . "\n\n";

unlink("temp.pp.dep");
unlink("temp.pp");
foreach my $objfile (keys %obj) {
    my $cfile = $obj{$objfile};
    my @deps;
    if(! -e $cfile) {
        print STDERR "Ignoring dependencies for $cfile\n";
        @deps = ($cfile);
    } else {
        my $cmd = "$pp -o temp.pp $cfile";
        print "$cmd\n";
        if(system($cmd)) {
            print STDERR "Failed to build dependencies for $cfile\n";
            close $outFH;
            unlink "$depfile";
            exit 1;
        }
        my $dep = `cat temp.pp.dep`; chomp($dep);
        @deps = split(/\s+/, $dep);
    }
    my $depstr = "$objfile:";
    my %seen;
    foreach (@deps) {
        s/"//g;
        next if(/^\\/);
        s/\\/\//g;
        next if($seen{$_});
        $seen{$_} = 1;
        $depstr .= " $_";
    }
    print $outFH "$depstr\n";
    print $outFH "\t\$(PIC_CC) \$<\n\n";
}
close $outFH;
unlink("temp.pp.dep");
unlink("temp.pp");

